<?php
namespace app\www\controller;
use x\my\pay\Alipay;
class Order extends Base{

    //创建订单
    public function createOrder(){
        $d = $this->post();
        $pay_money = $d["payPrice"];
        cookie('js_url',url('/user/myCart'));
        $rule = [
            'goods_ids' => 'require',
            'address_id' => 'require',
            'payPrice' => 'require',
        ];
        $msg = [
            'goods_ids.require' => '未选中商品',
            'address_id.require' => '未选择收货地址',
            'payPrice.require' => '参数错误',
        ];

        check($rule, $msg, $d);

        $goods_ids = $d['goods_ids'];
        //创建订单编号
        $order_goods_no =  com_order_no();
        $model = m("orderGoods","c");
        $rs = $model->createOrder($this->userinfo['id'],$goods_ids,$order_goods_no,$d["address_id"]);
        if($rs){
            //删除购物车商品
            foreach ($goods_ids as $k => $v) {
                $map = [];
                $map[] = ["and", "goods_price_id", "=", $k];
                $map[] = ["and", "user_id", "=", $this->userinfo["id"]];
                $w = where($map);
                $this->db->query("delete from order_cart $w[0]",$w[1]);
            }
            //如果用户余额大于订单总价，支付成功
            if($pay_money <= 0){
                $this->payOk($order_goods_no);
            }
            //充值余额
            $order_no = m('recharge','c')->rechargeMoney($this->userinfo['id'],$pay_money,1,"order_goods",$rs);
            if($order_no){
                $pay = new Alipay();
                $formhtml = $pay->buildRequestForm($order_no, $pay_money, '消费充值');
                suc(['formhtml'=>$formhtml,'order_no'=>$order_no,"order_goods_no"=>$order_goods_no]);
            }

        }
        err("订单创建失败");
    }

    //循环查询用户余额充值订单是否完成
    public function forEachUserRecharge(){
        $d = $this->post();
        if(!isset($d["order_no"])){
            err("订单不存在!");
        }
        $order_no = $d["order_no"];
        //查询商品订单
        $map = [];
        $map[] = ["and","order_no","=",$order_no];
        $map[] = ["and","pay_status","=",1];
        $w = where($map);
        $recharge_info = $this->db->query("select * from recharge $w[0]",$w[1],1);
        if(!$recharge_info){
            err("订单未支付!");
        }
        $this->payOk($d['order_goods_no']);
    }

    /**
     * [payOk 订单支付成功]
     * @param  string $order_no [订单编号]
     * @return [type]           [json]
     */
    private function payOk($order_no=''){
        if(!$order_no){
            cookie('js_url',url('/user/myCart'));
            err("参数错误!");
        }
        //查询商品订单
        $map = [];
        $map[] = ["and","order_no","=",$order_no];
        $w = where($map);
        $order_goods_list = $this->db->query("select * from order_goods $w[0]",$w[1]);
        if(empty($order_goods_list)){
            cookie('js_url',url('/user/myCart'));
            err("订单不存在!");
        }
        $order_total_price = $order_goods_list[0]['order_total_money'];
        if($this->userinfo["money"] < $order_total_price){
            cookie('js_url',url('/user/myCart'));
            err("用户余额不足!".$this->userinfo["money"]);
        }
        $this->db->begin();
        $mysql = [];
        //修改订单支付状态
        $d = ["pay_status"=>1];
        $map = ['order_no=?', [$order_no]];
        $mysql[] = $this->db->update("order_goods",$d,$map);
        foreach ($order_goods_list as $k => $v) {
            m('goods','c')->updateStock($v['nums'],$v['goods_price_id']);
        }

        #插入账单
        $mysql[] = m('Userbill', 'xcom')->doit($order_no, $this->userinfo['id'], 200, 'order_goods',  $order_goods_list[0]['id'],  $order_total_price, 'money','消费',0);
        $rs = $this->db->end($mysql);
        if(!$rs){
            log_test('wxpay_result_db',$mysql);
            err('支付账单失败');
        }
        //添加金额日志
        cookie('js_url',url('/user/orderlist'));
        cookie('js_msg',"支付成功");
        suc();
    }

    //订单详情
    public function detail(){
        $d = $this->get();
        $order_no = "";
        if(isset($d['out_trade_no'])){ //同步支付回调
            $model = m("Recharge","c");
            $order_goods_info = $model->getRechargeTableInfo($d['out_trade_no']);
            $order_no = $order_goods_info['order_no'];
        }else{
            $order_no = $d["order_no"];
        }
        if(!$order_no){
            cookie('js_url',url('/user/orderList'));
            err("订单不存在!");
        }
        $sql = "select * from order_goods where order_no = ? order by id desc";
        $rs = $this->db->query($sql,[$order_no]);
        $rule = [
            'pay_status' => function($v){return c("type.pay_status.{$v}");},
            'fahuo_status' => function($v){return c("type.fahuo_status.{$v}");},
            'create_time' => 'com_time_format',
        ];
        $data = com_format($rs,$rule);
        $this->fetch(['info'=>$data],'',false);
    }

    /**
     * 申请退款
     * [refundmoney description]
     * @return [type] [description]
     */
    public function refundmoney(){
        $d = $this->post();
        if(!isset($d['id'])){
            err("参数错误!");
        }
        $info = $this->db->query('select * from order_goods where id=? and user_id=?',[$d['id'],$this->userinfo['id']],1);
        if(!$info){
            err("订单不存在!");
        }
        $m = m('orderGoods','c');
        $rs = $m->apply_refund($d['id']);
        if($rs){
            cookie('js_function','preload');
            cookie('js_msg',"申请成功");
            suc();
        }else{
            err($m->getError());
        }
    }
}
?>
